package com.atguigu.gulimal.ssoclient.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {



    @Value("${xxl.sso.server}")
    private String ssoServerUrl;


    /**
     * 无需登陆的页面
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    /**
     *
     * @param model
     * @param session
     * @param token  只要去ssoserver 登录成功调回来的就带上token
     * @return
     */
    @GetMapping("/employees")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token", required = false) String token) {
        if (!StringUtils.isEmpty(token)){
            //去ssoserver登录成功带来回的token，通过redis查找用户名

            //去ssoServer获取当前token真正对应的信息
            RestTemplate restTemplate = new RestTemplate();
            String url = ssoServerUrl + "/userInfo?token=" + token;
            ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser",body);

        }
        if (token == null) {
            //没登录
            return "redirect:" + ssoServerUrl + "/login.html" + "?redirect_url=http://client1.com:8081/employees";
        } else {
            List<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps", emps);
            return "list";
        }

    }

}
